package cn.szzsi.service;

import cn.szzsi.common.kit.CommonUtil;
import cn.szzsi.common.model.Member;
import cn.szzsi.common.model.Orders;
import cn.szzsi.common.model.SiteConfig;
import cn.szzsi.common.model.UserBalanceDetail;
import cn.szzsi.core.kit.UtilDate;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.*;

/**
 * 余额明细
 * Created by zhengy on 2017/2/27.
 */
public class UserBalanceDetailService {
    public static final UserBalanceDetailService service = new UserBalanceDetailService();

    //获取培养津贴列表(admin)
    public Map<String,Object> getPyjtList(Integer rankLevel, String shopId, String profitDate ){
        Map<String,Object> result = new HashMap<String,Object>();

        List<Record> lr = Db.find("select m.code,m.username,m.phone,b.*  from mall_member m right join mall_user_balance_detail b on m.id=b.mid where b.type='1' and b.rankLevel=? and b.profitDate=? and b.shopId=? order by rewardNum",rankLevel,profitDate,shopId);
        result.put("data",lr);
        result.put("rewardNum",lr.size());//分红人数

        SiteConfig siteConfig= SiteConfig.dao.findByShopId(shopId);
        Integer rewardPercent= siteConfig.getInt("rewardPercent"+rankLevel);
        result.put("rewardPercent",rewardPercent);//分红比例

        //获取所选当天的营业额(totalAmount)
        Orders orders=new Orders();
        String profitDateEnd=profitDateEnd(profitDate);//截止到分红当天凌晨加上24小时之后的时间
        orders=orders.findFirst("select sum(totalAmount) totalAmount from mall_orders where paymentStatus='2' and uid=? and createDate>? and createDate<=?",shopId,profitDate,profitDateEnd);
        BigDecimal totalAmount=orders.getBigDecimal("totalAmount");
        if(totalAmount==null){
            totalAmount=new BigDecimal(0);
        }
        result.put("totalAmount",totalAmount);//近日营业额
        result.put("rewardCash",totalAmount.multiply(new BigDecimal(rewardPercent).divide(new BigDecimal(100))));//分红金额
        return result;
    }

    //获取辅导津贴列表(admin)
    public Map<String,Object> getFdjtList(Integer rankLevel, String uid){
        Map<String,Object> result = new HashMap<String,Object>();
        List<Record> lr = Db.find("select m.code,m.username,m.phone,b.*  from mall_member m right join mall_user_balance_detail b on m.id=b.mid where b.type='2' and b.rankLevel=? and b.shopId=? order by b.createDate desc",rankLevel,uid);
        result.put("data",lr);
        result.put("rewardNum",lr.size());//分红人数

        SiteConfig siteConfig= SiteConfig.dao.findByShopId(uid);
        Integer orderPercent= siteConfig.getInt("orderPercent"+rankLevel);
        result.put("orderPercent",orderPercent);//分成比例
        return result;
    }

    //生成培养津贴(admin)
    public void createPyjt(String shopId, Integer dataLevel, String profitDate){
        SiteConfig siteConfig= SiteConfig.dao.findByShopId(shopId);
        //根据输入的级别来获取该级别需要直荐多少人及分销的比例
        Integer rewardPercent=siteConfig.getInt("rewardPercent"+dataLevel);//分销比例

        //获取所选当天的营业额(totalAmount)
        Orders orders=new Orders();
        String profitDateEnd=profitDateEnd(profitDate);//截止到分红当天凌晨加上24小时之后的时间
        orders=orders.findFirst("select sum(totalAmount) totalAmount from mall_orders where paymentStatus='2' and uid=? and createDate>? and createDate<=?",shopId,profitDate,profitDateEnd);
        BigDecimal totalAmount=orders.getBigDecimal("totalAmount");
        if(totalAmount==null){
            totalAmount=new BigDecimal(0);
        }

        //根据直荐人数查看那些会员符合条件
        String sqlplus="";
        sqlplus="total>="+siteConfig.getInt("rewardnum"+dataLevel)+"";
        BigDecimal mulRewardPercent=new BigDecimal(rewardPercent).divide(new BigDecimal(100));
        List<Member> list= Member.dao.find("select m.id, m.code,m.username,m.phone, p.* from(select pid ,count(*) as total,shopid from mall_member where shopId='"+shopId+"' and memberRankId='dafc86f6aee04a8aa9c722689ef65b3y' and createDate<'"+profitDateEnd+"' and pid!='0' group by pid having "+sqlplus+" )p left join mall_member m on p.pid=m.id order by p.total");
        for(Member member:list){
            String mid=member.getStr("id");//会员id
            Long rewardnum=member.getLong("total");//直荐正式会员人数
            BigDecimal profit=totalAmount.multiply(mulRewardPercent).divide(new BigDecimal(list.size()),2, BigDecimal.ROUND_HALF_DOWN);//分红金额
            savePyjtInfo(mid,rewardnum,profit,0,dataLevel,shopId,profitDate, UserBalanceDetail.BalanceType.pyjt.ordinal());//培养津贴明细
        }
    }

    public List<UserBalanceDetail> isExitPyjtRecord(Integer rankLevel, String createDate, String uid){
        return UserBalanceDetail.dao.find("select id from mall_user_balance_detail where rankLevel=? and profitDate=? and shopId=?",rankLevel,createDate,uid);
    }
    //判断所选日期培养津贴是否已分配
    public List<UserBalanceDetail> isDistributionPyjt(Integer rankLevel, String profitDate, String shopId){
        return UserBalanceDetail.dao.find("select id from mall_user_balance_detail b  where b.type='1' and b.rankLevel=? and b.profitDate=? and b.shopId=? and status='0'",rankLevel,profitDate,shopId);
    }
    //一键分配培养津贴(admin)
    public void distributionPyjt(Integer rankLevel, String profitDate, String shopId){
        //根据dataLevel,profitDate,uid获取培养津贴列表
        List<UserBalanceDetail> lr = UserBalanceDetail.dao.find("select * from mall_user_balance_detail b  where b.type='1' and b.rankLevel=? and b.profitDate=? and b.shopId=? and status='0'",rankLevel,profitDate,shopId);
        for(UserBalanceDetail bUserBalanceDetail:lr){
            bUserBalanceDetail.set("status",1).update();//一键分配后,改变分红状态
            UserBalanceService.service.updateBalance(Member.dao.findById(bUserBalanceDetail.getStr("mid")),bUserBalanceDetail.getBigDecimal("addMoney"));//更新会员余额结果
        }
    }

    //生成辅导津贴(web)
    public void createFdjt(String uid, Orders orders, Member member){
        SiteConfig siteConfig= SiteConfig.dao.findByShopId(uid);//查询店铺配置信息
        BigDecimal totalIncome1=new BigDecimal(siteConfig.getInt("totalIncome1")*10000);//单位万
        BigDecimal totalIncome2=new BigDecimal(siteConfig.getInt("totalIncome2")*10000);
        BigDecimal totalIncome3=new BigDecimal(siteConfig.getInt("totalIncome3")*10000);
        BigDecimal totalIncome4=new BigDecimal(siteConfig.getInt("totalIncome4")*10000);
        BigDecimal totalIncome5=new BigDecimal(siteConfig.getInt("totalIncome5")*10000);
        BigDecimal totalIncome6=new BigDecimal(siteConfig.getInt("totalIncome6")*10000);

        BigDecimal orderPercent1=new BigDecimal(siteConfig.getInt("orderPercent1")).divide(new BigDecimal(100));
        BigDecimal orderPercent2=new BigDecimal(siteConfig.getInt("orderPercent2")).divide(new BigDecimal(100));
        BigDecimal orderPercent3=new BigDecimal(siteConfig.getInt("orderPercent3")).divide(new BigDecimal(100));
        BigDecimal orderPercent4=new BigDecimal(siteConfig.getInt("orderPercent4")).divide(new BigDecimal(100));
        BigDecimal orderPercent5=new BigDecimal(siteConfig.getInt("orderPercent5")).divide(new BigDecimal(100));
        BigDecimal orderPercent6=new BigDecimal(siteConfig.getInt("orderPercent6")).divide(new BigDecimal(100));

        String pid=member.getStr("pid");//上级会员id
        String pids=member.getStr("pids");//所有上级字符串
        List<String> list=new ArrayList();
        String pidsArray[];
        if(!"0".equals(pids)){//
            pidsArray=pids.split(",");//字符串转换为数组
            String reservePidsArray[]=new String[pidsArray.length];
            for(int i=0;i<pidsArray.length;i++){//将所有上级数据倒叙排列
                reservePidsArray[i]=pidsArray[pidsArray.length-1-i];
            }
            list=new ArrayList(Arrays.asList(reservePidsArray));//数组转换为集合(该集合存放的是所有上级id,并且按照推荐先后顺序排列)
        }

        int fdjtPercent=siteConfig.getInt("fdjtPercent");//辅导津贴百分比
        BigDecimal productTotalPrice=orders.getBigDecimal("productTotalPrice");//该订单的总金额
        String orderSn=orders.getStr("orderSn");//订单编号
        BigDecimal profit=new BigDecimal(0);//分成金额

        for(String memberId:list){//遍历所有上级id
            Member pMember= Member.dao.findById(memberId);//上级会员信息
            BigDecimal totaIncome=getTotalIncome(memberId);//上级会员总收入
            int memberLevel=0;//会员级别
            //查看是否是正式会员(针对开元一通)
            if(!"dafc86f6aee04a8aa9c722689ef65b3y".equals(pMember.getStr("memberRankId"))){
                continue;//如果上级不是正式会员,结束本次循环,进行下一轮循环
            }
            if(totaIncome.compareTo(totalIncome6)>=0 && fdjtPercent>0){
                if(fdjtPercent>=siteConfig.getInt("orderPercent6")){
                    profit=productTotalPrice.multiply(orderPercent6);
                    fdjtPercent=fdjtPercent-siteConfig.getInt("orderPercent6");
                }else{
                    profit=productTotalPrice.multiply(new BigDecimal(fdjtPercent));
                    fdjtPercent=0;
                }
                memberLevel=6;
            }else if(totaIncome.compareTo(totalIncome5)>=0 && fdjtPercent>0){
                if(fdjtPercent>=siteConfig.getInt("orderPercent5")){
                    profit=productTotalPrice.multiply(orderPercent5);
                    fdjtPercent=fdjtPercent-siteConfig.getInt("orderPercent5");
                }else{
                    profit=productTotalPrice.multiply(new BigDecimal(fdjtPercent));
                    fdjtPercent=0;
                }
                memberLevel=5;
            }else if (totaIncome.compareTo(totalIncome4)>=0 && fdjtPercent>0){
                if(fdjtPercent>=siteConfig.getInt("orderPercent4")){
                    profit=productTotalPrice.multiply(orderPercent4);
                    fdjtPercent=fdjtPercent-siteConfig.getInt("orderPercent4");
                }else{
                    profit=productTotalPrice.multiply(new BigDecimal(fdjtPercent));
                    fdjtPercent=0;
                }
                memberLevel=4;
            }else if (totaIncome.compareTo(totalIncome3)>=0 && fdjtPercent>0){
                if(fdjtPercent>=siteConfig.getInt("orderPercent3")){
                    profit=productTotalPrice.multiply(orderPercent3);
                    fdjtPercent=fdjtPercent-siteConfig.getInt("orderPercent3");
                }else{
                    profit=productTotalPrice.multiply(new BigDecimal(fdjtPercent));
                    fdjtPercent=0;
                }
                memberLevel=3;
            }else if (totaIncome.compareTo(totalIncome2)>=0 && fdjtPercent>0){
                if(fdjtPercent>=siteConfig.getInt("orderPercent2")){
                    profit=productTotalPrice.multiply(orderPercent2);
                    fdjtPercent=fdjtPercent-siteConfig.getInt("orderPercent2");
                }else{
                    profit=productTotalPrice.multiply(new BigDecimal(fdjtPercent));
                    fdjtPercent=0;
                }
                memberLevel=2;
            }else if (totaIncome.compareTo(totalIncome1)>=0 && fdjtPercent>0){
                if(fdjtPercent>=siteConfig.getInt("orderPercent1")){
                    profit=productTotalPrice.multiply(orderPercent1);
                    fdjtPercent=fdjtPercent-siteConfig.getInt("orderPercent1");
                }else{
                    profit=productTotalPrice.multiply(new BigDecimal(fdjtPercent));
                    fdjtPercent=0;
                }
                memberLevel=1;
            }
            //存入会员分层金额
            if(profit.compareTo(new BigDecimal(0))>0){
                UserBalanceService.service.updateBalance(Member.dao.findById(memberId),profit);//更新会员余额结果
                saveFdjtInfo(memberId,profit,totaIncome,0,memberLevel,orderSn,uid);//辅导津贴明细
            }
            if(fdjtPercent<=0){
                break;//辅导津贴百分比小于等于零时,结束循环体,不再对下一个上级会员进行分成
            }

        }
    }

    /**
     *  总收入(佣金+培养津贴+辅导津贴)
     * @param memberId 会员ID
     * @return
     */
    public BigDecimal getTotalIncome(String memberId){
        String expectSql="SELECT IFNULL(sum(addMoney),0)totaIncome FROM `mall_user_balance_detail` where mid='"+memberId+"' and (type='0' or (type='1' and status=1) or type='2')";
        BigDecimal totaIncome= Db.queryColumn(expectSql);
        return totaIncome;
    }

    /**
     * 支付明细
     * @param mid 会员id
     * @param addMoney 交易金额
     * @param type 交易类型
     * @param shopId 店铺id
     * @param orderSn 订单编号
     */
    public void savePaymentInfo(String mid, BigDecimal addMoney, int type, String shopId, String orderSn){
        UserBalanceDetail userBalanceDetail =new UserBalanceDetail();
        userBalanceDetail.set("id", CommonUtil.getUUID());
        userBalanceDetail.set("mid",mid);
        userBalanceDetail.set("addMoney",addMoney);
        userBalanceDetail.set("shopId",shopId);
        userBalanceDetail.set("orderSn",orderSn);
        userBalanceDetail.set("type",type);
        userBalanceDetail.set("createDate",new Date());
        userBalanceDetail.save();
    }

    /**
     * 后台代充值明细
     * @param mid 会员id
     * @param addMoney 交易金额
     * @param type 交易类型
     * @param shopId 店铺id
     */
    public void saveAdminRecharge(String mid,BigDecimal addMoney,int type,String shopId){
        UserBalanceDetail userBalanceDetail =new UserBalanceDetail();
        userBalanceDetail.set("id", CommonUtil.getUUID());
        userBalanceDetail.set("mid",mid);
        userBalanceDetail.set("addMoney",addMoney);
        userBalanceDetail.set("shopId",shopId);
        userBalanceDetail.set("type",type);
        userBalanceDetail.set("createDate",new Date());
        userBalanceDetail.save();
    }

    /**
     *  后台退款
     * @param mid 会员id
     * @param addMoney 交易金额
     * @param type 交易类型
     * @param shopId 店铺id
     * @param orderSn 订单编号
     */
    public void saveAdminRefund(String mid, BigDecimal addMoney, int type, String shopId, String orderSn){
        UserBalanceDetail userBalanceDetail =new UserBalanceDetail();
        userBalanceDetail.set("id", CommonUtil.getUUID());
        userBalanceDetail.set("mid",mid);
        userBalanceDetail.set("addMoney",addMoney);
        userBalanceDetail.set("shopId",shopId);
        userBalanceDetail.set("orderSn",orderSn);
        userBalanceDetail.set("type",type);
        userBalanceDetail.set("createDate",new Date());
        userBalanceDetail.save();
    }

    /**
     * 会员提现明细
     * @param mid 会员id
     * @param addMoney 交易金额
     * @param type 交易类型
     * @param shopId 店铺id
     */
    public void saveToCashing(String mid,BigDecimal addMoney,int type,String shopId){
        UserBalanceDetail userBalanceDetail =new UserBalanceDetail();
        userBalanceDetail.set("id", CommonUtil.getUUID());
        userBalanceDetail.set("mid",mid);
        userBalanceDetail.set("addMoney",addMoney);
        userBalanceDetail.set("shopId",shopId);
        userBalanceDetail.set("type",type);
        userBalanceDetail.set("createDate",new Date());
        userBalanceDetail.save();
    }


    /**
     * 新户注册赠送金额
     * @param mid 会员id
     * @param addMoney addMoney 交易金额
     * @param type 交易类型
     * @param shopId 店铺id
     */
    public void saveRegisterMoney(String mid,BigDecimal addMoney,int type,String shopId){
        UserBalanceDetail userBalanceDetail =new UserBalanceDetail();
        userBalanceDetail.set("id", CommonUtil.getUUID());
        userBalanceDetail.set("mid",mid);
        userBalanceDetail.set("addMoney",addMoney);
        userBalanceDetail.set("shopId",shopId);
        userBalanceDetail.set("type",type);
        userBalanceDetail.set("createDate",new Date());
        userBalanceDetail.setMemo("新户注册赠送金额");
        userBalanceDetail.save();
    }

    /**
     * 分销佣金明细
     * @param mid 会员ID
     * @param addMoney 返佣金额
     * @param type 交易类型
     * @param shopId 店铺ID
     * @param orderSn 订单编号
     * @param fromuid 返佣来源会员的id
     * @param level 当前会员在返佣的第几级
     * @param rate 返佣的比例
     */
    public void saveFenXiaoInfo(String mid, BigDecimal addMoney, int type, String shopId, String orderSn, String fromuid, Integer level, int rate){
        UserBalanceDetail userBalanceDetail=new UserBalanceDetail();
        userBalanceDetail.set("id", CommonUtil.getUUID());
        userBalanceDetail.set("mid",mid);
        userBalanceDetail.set("addMoney",addMoney);
        userBalanceDetail.set("shopId",shopId);
        userBalanceDetail.set("orderSn",orderSn);
        userBalanceDetail.set("fromuid",fromuid);
        userBalanceDetail.set("level",level);
        userBalanceDetail.set("rate",rate);
        userBalanceDetail.set("type",type);
        userBalanceDetail.set("createDate",new Date());
        userBalanceDetail.save();
    }

    /**
     *  培养津贴明细
     * @param mid 会员ID
     * @param rewardnum 直荐会员数
     * @param addMoney  培养津贴分红金额
     * @param status 状态
     * @param rankLevel 级别
     * @param shopId 店铺ID
     * @param profitDate 培养津贴日期
     */
    public void savePyjtInfo(String mid, Long rewardnum, BigDecimal addMoney, Integer status, Integer rankLevel, String shopId, String profitDate, int type){
        UserBalanceDetail userBalanceDetail=new UserBalanceDetail();
        userBalanceDetail.set("id", CommonUtil.getUUID());
        userBalanceDetail.set("mid",mid);
        userBalanceDetail.set("rewardnum",rewardnum);
        userBalanceDetail.set("addMoney",addMoney);
        userBalanceDetail.set("status",status);
        userBalanceDetail.set("rankLevel",rankLevel);
        userBalanceDetail.set("shopId",shopId);
        userBalanceDetail.set("profitDate",profitDate);
        userBalanceDetail.set("type",type);
        userBalanceDetail.set("createDate",new Date());
        userBalanceDetail.save();

    }

    /**
     *  辅导津贴明细
     * @param mid 会员ID
     * @param addMoney 辅导津贴金额
     * @param totalIncome 总收入
     * @param status 状态
     * @param rankLevel 级别
     * @param orderSn 订单编号
     * @param shopId 店铺ID
     */
    public void saveFdjtInfo(String mid, BigDecimal addMoney, BigDecimal totalIncome, Integer status, Integer rankLevel, String orderSn, String shopId){
        UserBalanceDetail userBalanceDetail=new UserBalanceDetail();
        userBalanceDetail.set("mid",mid);
        userBalanceDetail.set("addMoney",addMoney);
        userBalanceDetail.set("totalIncome",totalIncome);
        userBalanceDetail.set("status",status);
        userBalanceDetail.set("rankLevel",rankLevel);
        userBalanceDetail.set("orderSn",orderSn);
        userBalanceDetail.set("shopId",shopId);
        userBalanceDetail.save();

    }


    /**
     * 根据交易类型,获取该会员总的费用金额
     * @param mid 会员id
     * @param type 交易类型
     * @return
     */
    public BigDecimal getAmountBalanceByMidAndType(String mid,Integer type){
        BigDecimal money= Db.queryColumn("select ifnull(sum(addMoney),0)money from mall_user_balance_detail where mid=? and type=?",mid,type);
        return money;
    }

    //获取分红当天凌晨加上24小时之后的时间
    public String profitDateEnd(String profitDate){
        Long strTime;//所选时间戳
        Long timeEnd;//24小时之后的时间戳
        String profitDateEnd="";//截止到分红当天凌晨加上24小时之后的时间
        try {
            strTime= UtilDate.strToTimestamp(profitDate);//获取分红日期的时间戳
            timeEnd=strTime+86400000;
            profitDateEnd= UtilDate.timestampToDateStr(timeEnd);//时间戳转换成日期字符串
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return profitDateEnd;
    }

}
